package com.vae.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.util.DButil;
import com.vae.domain.Person;

public class PersonDaoImpl implements PersonDao {

	private QueryRunner runner = null;//查询运行器
	public PersonDaoImpl() {
		runner = new QueryRunner();
	}
	@Override//增加
	public void add(Person person) throws SQLException {
		// TODO Auto-generated method stub
		String sql = "insert into person(name,age,description)values(?,?,?)";
		runner.update(DButil.getConnection(), sql, person.getName(),person.getAge(),person.getDescription());
	}

	@Override//更新
	public void update(Person person) throws SQLException {
		// TODO Auto-generated method stub
	       String sql = "update person set name=?,age=?,description=? where id=?";
	       runner.update(DButil.getConnection(), sql, person.getName(),person.getAge(),person.getDescription(),person.getId());
	}

	@Override//删除
	public void delete(int id) throws SQLException {
		// TODO Auto-generated method stub
		String sql = "delete from person where id=?";
		runner.update(DButil.getConnection(), sql, id);
	}

	@Override//查找
	public Person findById(int id) throws SQLException {
		// TODO Auto-generated method stub
		String sql = "select name,age,description from person where id=?";
		Person p = runner.query(DButil.getConnection(), sql, new BeanHandler<Person>(Person.class),id);
		return p;
	}

	@Override//所有
	public List<Person> findAll() throws SQLException {
		// TODO Auto-generated method stub
        String sql = "select name,age,description from person";
        List<Person> persons = runner.query(DButil.getConnection(), sql, new BeanListHandler<Person>(Person.class));
        return persons;
	}

	//方法：使用ScalarHandler查询一共有几条记录
	@Override
	public long personCount() throws SQLException {
		// TODO Auto-generated method stub
		String sql = "select count(id) from person";
		return runner.query(DButil.getConnection(),sql, new ScalarHandler<Long>());
		
	}

}
